import React, { useEffect, useState } from "react";
import { get_synthesis, saveOrUpdate } from "@/api/emr/index";
import { BasicTable, useTable } from "@/components/Table";
import cloneDeep from "lodash/cloneDeep";
import { Card, Col, Row, Radio, Checkbox, Button, Input } from "antd";

export default function emr() {
	const [synthesisList, setSynthesisList] = useState({
		nameEn: "",
		blocks: []
	});
	const [loading, setLoading] = useState(true);
	const [tableRows, setTableRows] = useState([]);
	const [tableCols, setTableCols] = useState([]);
	// 存储输入框的值
	const [inputValues, setInputValues] = useState({});
	// 存储输入框的显示状态，使用对象存储，以 record.blockId、columnDataIndex 和 itemId 为键
	const [inputVisible, setInputVisible] = useState({});

	// 自定义渲染函数，根据 dataType 进行不同的渲染
	const renderColumn = (text: string, record: any, index: any) => {
		const column = tableCols[index];
		if (column.dataType === "OPTIONS") {
			if (Array.isArray(text)) {
				return (
					<div>
						<Radio.Group onChange={e => handleRadioChange(record, column.dataIndex, e.target)}>
							{text.map((item, itemIndex) => (
								<div key={`${record.blockId}-${column.dataIndex}-${itemIndex}-${item.itemId || "default"}`}>
									<Radio value={item.itemId}>{item.nameCn}</Radio>
									{inputVisible[`${record.blockId}-${column.dataIndex}-${item.itemId}`] && (
										<Input
											value={inputValues[`${record.blockId}-${column.dataIndex}-${item.itemId}`] || ""}
											onChange={e => handleInputChange(`${record.blockId}-${column.dataIndex}-${item.itemId}`, e.target.value)}
											style={{ marginLeft: "10px" }}
										/>
									)}
								</div>
							))}
						</Radio.Group>
					</div>
				);
			}
		} else if (column.dataType === "SUBJECT") {
			return (
				<div>
					{record[column.dataIndex].nameCn} ({record[column.dataIndex].nameEn})
				</div>
			);
		}
		return text;
	};
	const columns = tableCols.map((col, index) => ({
		...col,
		render: (text: string, record: any) => renderColumn(text, record, index)
	}));

	// 配置 table
	const [registerTable] = useTable({
		dataSource: tableRows,
		columns,
		bordered: true,
		pagination: false
	});

	// table 组件中 Radio 变化的函数
	const handleRadioChange = (record: any, columnDataIndex: string, target: any) => {
		// 删除 record 的 key 属性
		const newRecord = { ...record };
		console.log("record", record);
		console.log("columnDataIndex", columnDataIndex);
		console.log("value", target);
		// 创建一个新的数据副本
		const newData = cloneDeep(synthesisList);
		const blockIndex = newData.blocks.findIndex(block => block.blockId === newRecord.blockId);
		if (blockIndex !== -1) {
			// 更新 tableRows 中的 result 字段
			const tableRowIndex = newData.blocks[blockIndex].tableRows.findIndex(row =>
				row[columnDataIndex]?.some(item => item.itemId === target.value)
			);
			if (tableRowIndex !== -1) {
				const items = newData.blocks[blockIndex].tableRows[tableRowIndex][columnDataIndex];
				items.forEach(item => {
					if (item.itemId === target.value) {
						item.result = true;
					} else {
						item.result = false;
					}
				});
				// 根据选中项的 children 属性更新 inputVisible 状态
				const selectedItem = items.find(item => item.itemId === target.value);
				setInputVisible(prev => ({
					...prev,
					[`${record.blockId}-${columnDataIndex}-${target.value}`]:
						Array.isArray(selectedItem?.children) && selectedItem.children.length > 0
				}));
			}
			// 更新状态
			setSynthesisList(newData);
		} else {
			console.error("未找到匹配的 block", record);
		}
	};

	// 处理 input 组件的输入变化
	const handleInputChange = (key: string, value: string) => {
		setInputValues(prevValues => ({ ...prevValues, [key]: value }));
	};

	// card 组件中 Checkbox 变化的函数
	const handleChange = (index: number, p: number, i: number, event: any) => {
		console.log(index, p, i, event);
		// 创建一个新的数据副本，避免直接修改状态
		const newData = cloneDeep(synthesisList);
		// 更新相应索引的数据
		newData.blocks[index].subjects[p].items[i].result = event.target.checked;
		// 更新状态
		setSynthesisList(newData);
	};

	// 获取页面组件
	const getComponent = (data: any, index: number, p: number) => {
		let types: any = [];
		data.forEach(item => {
			types.push(item.inputType);
		});
		if (types.includes("CHECKBOX")) {
			let defaultValue = data.filter(item => item.result).map(v => v.itemId);
			return (
				<Checkbox.Group defaultValue={defaultValue}>
					{data.map((v, i) => (
						<Checkbox
							key={`${index}-${p}-${i}-${v.itemId}`}
							checked={v.result}
							onChange={e => handleChange(index, p, i, e)}
							value={v.itemId}
							style={{ marginBottom: "10px" }}
						>
							{v.nameCn}
						</Checkbox>
					))}
				</Checkbox.Group>
			);
		} else if (types.includes("RADIO")) {
			let defaultValue = null;
			for (let item of data) {
				if (item.result) {
					defaultValue = item.itemId;
					break;
				}
			}
			return (
				<Radio.Group defaultValue={defaultValue}>
					{data.map((v, i) => (
						<Radio
							key={`${index}-${p}-${i}-${v.itemId}`}
							onChange={e => handleChange(index, p, i, e)}
							value={v.itemId}
							style={{ marginBottom: "10px" }}
						>
							{v.nameCn}
						</Radio>
					))}
				</Radio.Group>
			);
		} else {
			console.log("TEXT");
		}
	};

	// 提交
	const submit = async () => {
		const newData = { ...synthesisList };
		newData.rcptId = "15936";
		newData.patId = "23539";
		await saveOrUpdate(newData);
		location.reload();
	};

	// 立即执行的函数
	useEffect(() => {
		const get_list = async () => {
			const res = await get_synthesis({ fromId: "2", rcptId: "15936" });
			console.log(res);
			setSynthesisList(res);
			res.blocks.forEach(item => {
				if (item.tableRows) {
					const newTableRows = item.tableRows.map(row => ({ ...row, blockId: item.blockId }));
					setTableRows(newTableRows);
				}
				if (item.tableCols) {
					setTableCols(item.tableCols);
				}
			});
			setLoading(false);
			// 初始化 inputVisible 状态
			setInputVisible({});
			res.blocks.forEach(block => {
				if (block.tableRows) {
					block.tableRows.forEach(row => {
						row.forEach(item => {
							if (Array.isArray(item)) {
								item.forEach(subItem => {
									if (Array.isArray(subItem)) {
										subItem.forEach(subSubItem => {
											setInputVisible(prev => ({
												...prev,
												[`${block.blockId}-${item.columnDataIndex}-${subSubItem.itemId}`]: false
											}));
										});
									}
								});
							}
						});
					});
				}
			});
		};
		get_list();
	}, []);

	return (
		<div className="page block overflow-auto">
			<div className="header">
				<div className="text-center font-size-9">{synthesisList.nameCn}</div>
				<Button type="primary" onClick={submit}>
					提交
				</Button>
				{synthesisList.blocks.map((item, index) => (
					<div key={item.blockId}>
						<div className="font-size-5">{item.nameCn}</div>
						{item.tableCols ? (
							<BasicTable columns={columns} register={registerTable}></BasicTable>
						) : (
							<Row gutter={16}>
								{item.subjects &&
									item.subjects.map((o, p) => (
										<Col span={4} key={`${index}-${p}-${o.subjsId}`}>
											<Card title={o.nameCn} style={{ marginTop: 16, overflow: "auto" }} loading={loading}>
												{getComponent(o.items || [], index, p)}
											</Card>
										</Col>
									))}
							</Row>
						)}
					</div>
				))}
			</div>
		</div>
	);
}
